package org.mspring.platform.web.render;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Gao Youbo
 * @since 2012-07-06 15:00:55
 */
public class JPEGRender extends AbstractResponseRender {

    private static final Logger log = LoggerFactory.getLogger(JPEGRender.class);

    private BufferedImage buffImg;

    public void setBuffImg(BufferedImage buffImg) {
        this.buffImg = buffImg;
    }

    public JPEGRender(BufferedImage buffImg) {
        this.buffImg = buffImg;
    }

    @Override
    public void render(HttpServletResponse response) {
        if (this.buffImg == null) {
            return;
        }

        // 禁止图像缓存。
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        response.setContentType("image/jpeg");
        try {
            ServletOutputStream out = response.getOutputStream();
            ImageIO.write(buffImg, "JPEG", out);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }
}
